﻿using Acme.ConcreteMixDesign.Dtos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Microsoft.AspNetCore.Routing.Template;
using Xceed.Words.NET;
using Xceed.Document.NET;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Collections;
using System.IO.Pipes;
using Acme.ConcreteMixDesign.Players;

namespace Acme.ConcreteMixDesign.JobRecords
{
    public class JobRecordAppService : CrudAppService<JobRecord, JobRecordDto, Guid, PagedAndSortedResultRequestDto, CreateJobRecordDto>, IJobRecordAppService
    {
        public readonly IJobRecordRepository _jobRecordRepository;
        public readonly IPlayerRepository _playerRepository;
        public JobRecordAppService(IJobRecordRepository repository,IPlayerRepository playerRepository) : base(repository)
        {
            _jobRecordRepository = repository;
            _playerRepository = playerRepository;
        }
        public async Task<Stream> GetWordAsync(Guid Jobid)
        {
            try
            {
                string appDataPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data");
                
                var i = await _jobRecordRepository.GetAsync(Jobid);
                var o = await _playerRepository.GetAsync(i.PlayerId);
                string path = Path.Combine(appDataPath, o.accounts + ".docx");
                if (i != null)
                {
                    using (DocX document = DocX.Create(path))
                    {
                        document.InsertParagraph(i.JobContent)
                            .FontSize(12)
                            .Italic()
                            .SpacingAfter(10)
                            .Alignment = Alignment.left;
                        // 保存文档
                        document.Save();
                    }
                    
                    // 读取并输出文件流
                    using (FileStream fileStream = new FileStream(path, FileMode.Open))
                    {
                         MemoryStream memoryStream = new MemoryStream();
                         fileStream.CopyTo(memoryStream);
                         memoryStream.Seek(0, SeekOrigin.Begin);
                         return memoryStream;
                    }
                }
                return new MemoryStream(); 
            }
            catch (Exception ex)
            {
                // 创建包含异常信息的 MemoryStream
                var errorStream = new MemoryStream();
                var writer = new StreamWriter(errorStream);
                writer.Write($"Error: {ex.Message}");
                writer.Flush();
                errorStream.Position = 0;

                return errorStream;
            }

        }
    }
}
